package com.v.im.imservice.config;

import com.v.im.commonmodule.utils.zkclient.balance.constans.ZkConstant;
import com.v.im.commonmodule.utils.zkclient.balance.server.RegistAndUnregistOperator;
import com.v.im.commonmodule.utils.zkclient.balance.server.ServerData;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.zookeeper.ZookeeperProperties;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ZkConfig {

    @Autowired
    private ZookeeperProperties zookeeperProperties;

    private ZkClient zkClient;

    private RegistAndUnregistOperator registAndUnregistOperator;

    private String currentServerPath;

    /**
     * 获取zk 连接地址
     */

    public void config() {
        String connectAddress = zookeeperProperties.getConnectString();
        if (StringUtils.isBlank(connectAddress)) {
            log.error(" 获取zookeeper连接地址为空！！！");
        }
        zkClient = new ZkClient(connectAddress, ZkConstant.SESSION_TIME_OUT,
                ZkConstant.CONNECT_TIME_OUT, new SerializableSerializer());
        registAndUnregistOperator = new RegistAndUnregistOperator(zkClient);

    }

    private ServerData createServerData(String ip, Integer port) {
        ServerData serverData = new ServerData();
        serverData.setLoad(ZkConstant.DEFAULT_LOAD);
        serverData.setHost(ip);
        serverData.setPort(port);
        return serverData;
    }

    /**
     * 注册 zk
     */
    public void registerServer(String ip, Integer port) {
        config();
        ServerData serverData = createServerData(ip, port);
        // 这里以端口号作为当前服务器对应的节点名，那么全路径节点名
        this.currentServerPath = ZkConstant.SERVERS_NODE_PATH.
                concat(ZkConstant.NODE_SEPARATOR).
                concat(serverData.getPort().toString());
        registAndUnregistOperator.setServerNodePath(currentServerPath);
        registAndUnregistOperator.regist(serverData);
    }

    /**
     *   解除注册
     */
    public void unRegisterServer() {
        registAndUnregistOperator.unRegist();
    }


    public ZkClient getZkClient() {
        return zkClient;
    }

    public String getCurrentServerPath() {
        return currentServerPath;
    }
}
